import type { RouteLocationNormalized, RouteLocationNormalizedLoaded } from "vue-router";

class StorageUtil {
  // 存储code
  setCode(code: string) {
    sessionStorage.setItem("code", code);
  }

  // 获取code
  getCode() {
    return sessionStorage.getItem("code");
  }

  // 判断是否存在code并且判断传入的code是否相等
  hasCode(code?: string) {
    const sessionCode = this.getCode();
    return !!sessionCode && sessionCode === code;
  }

  setRedirect(to: RouteLocationNormalized) {
    sessionStorage.setItem(
      "redirect",
      JSON.stringify({ path: to.path, query: to.query, params: to.params })
    );
  }

  getRedirect() {
    const redirect = sessionStorage.getItem("redirect");
    if (redirect) {
      return JSON.parse(redirect);
    } else {
      return { path: "/" };
    }
  }

  removeRedirect() {
    sessionStorage.removeItem("redirect");
  }

  queryRedirect(route: RouteLocationNormalizedLoaded): string {
    const redirect = route.query.redirect;
    console.log(redirect);
    return redirect ? (redirect as string) : "/";
  }
}

const storageUtil = new StorageUtil();

export { storageUtil };
